package tr.hba.jblog.view;

import java.io.Serializable;
import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import tr.hba.jblog.model.Post;
import tr.hba.jblog.model.User;
import tr.hba.jblog.model.UserStatus;
import tr.hba.jblog.service.IPostService;
import tr.hba.jblog.service.IUserService;

@Component("postAddChange")
@Scope("request")
public class PostAddChange implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private IPostService postService;
	private IUserService userService;

	private Post post = new Post();

	@Autowired
	public PostAddChange(IPostService postService, IUserService userService) {
		this.postService = postService;
		this.userService = userService;

	}

	public String saveOrUpdate() {

		FacesMessage facesMessage = null;

		if (post.getId() == null || post.getId() == 0) {
			
			User user = userService.findById(new Long(1));
			post.setCreatedBy(user);

			postService.create(post);
			post = new Post();

			facesMessage = new FacesMessage(FacesMessage.SEVERITY_INFO,
					"Post eklendi." + post.getTitle(), "OK");

		} else {

			postService.update(post);

			facesMessage = new FacesMessage(FacesMessage.SEVERITY_INFO,
					"Post güncellendi." + post.getTitle(), "OK");

		}

		FacesContext.getCurrentInstance().addMessage(null, facesMessage);

		return "post_list";

	}
	

	public Post getPost() {
		return post;
	}

	public void setPost(Post post) {
		this.post = post;
	}

}
